<template>
   <el-form :inline="true" :model="formInline" class="demo-form-inline">
    <el-form-item>
      <el-select v-model="formInline.region" placeholder="全部" @change="hanldeChange">
          <el-option
            v-for="item in formList"
            :key="item.value"
            :label="item.label"
            :value="item.id"
            >
          </el-option>
        </el-select>
        <el-input v-model="formInline.user" placeholder="" clearable v-if="formInline.region==''"/>

        <el-select v-model="formInline.user" placeholder="全部" v-else-if="formInline.region!=''&&formInline.region=='username'">
          <el-option
            v-for="item in tableDataList"
            :key="item.id"
            :label="item.name"
            :value="item.name"
            >
          </el-option>
        </el-select>
      <el-input v-model="formInline.user" placeholder="" clearable v-else-if="formInline.region!=''&&formInline.region!='ordertimestart'"/>
      <el-date-picker
        v-else
        v-model="formInline.date"
        type="daterange"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        :size="size"
        @change="handelDatePicker"
      />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="onSubmit">搜索</el-button>
      <!-- <el-button type="primary" @click="upload">导入</el-button> -->
      <el-upload
        class="upload-demo"
        multiple
        :http-request="handlePreview"
        accept=".xlsx, .xls"
      >
        <el-button type="primary">导入</el-button>
      </el-upload>
      
      <el-button type="primary" @click="onSubmit1(0)" :disabled="single.data">批量备注</el-button>
      <el-upload
        class="upload-demo"
        multiple
        :http-request="handlePreview1"
        accept=".xlsx, .xls"
      >
        <el-button type="primary">导入更新运费</el-button>
      </el-upload>
      <!-- <el-button type="primary" @click="onSubmit1(1)" :disabled="single.data">批量运费</el-button> -->
      <el-button type="primary" @click="daoChu">导出</el-button>
      <el-button type="primary" @click="onSubmit1(2)" :disabled="single.data&&isShop">批量签收状态</el-button>
      <el-button type="primary" @click="onSubmit1(3)" :disabled="single.data">批量采购成本</el-button>
    </el-form-item>
  </el-form>
  <el-table :data="tableData" style="width: 100%;height: 90%;" @select-all="handleSelectionChange" @select="handleSelection">
    <el-table-column type="selection" width="55" />
    <el-table-column prop="zip" label="图片" width="350">
      <template  #default="scope">
        <!-- <span>{{ scope.row.zip }}</span> -->
        <div v-for="(item,index) in scope.row.list" :key="index">

          <div class="flex">
            <el-popover placement="right" :width="260" trigger="hover">
            <img :src="item.img" width="200" height="260" />
            <template #reference>
              <img
                :src="item.img"
                style="max-height: 60px; max-width: 60px"
              />
            </template>
          </el-popover>
            <div class="flex_right">
              <!-- sku -->
              <div>
                <span style="color: #409eff;" @click="copy(item.sku)">{{ item.sku }}</span>
                x
                <span v-if="item.count==1" style="background: #ccc;color: #fff;border-radius: 100%;display: inline-block;width: 20px;height: 20px;text-align: center;line-height: 20px;">{{ item.count }}</span>
                <span v-else style="background: red;color: #fff;border-radius: 100%;display: inline-block;width: 20px;height: 20px;text-align: center;line-height: 20px;">{{ item.count }}</span>

              </div>
            </div>
          </div>
        </div>
      </template>
    </el-table-column>
    <el-table-column  prop="sellingpric" label="预估销售额" width="110" />
    <el-table-column prop="orderid" label="订单号"  width="180" >
      <template v-slot="scope">
        <div  v-for="(item,index) in scope.row.list" :key="index">
          <p  @click="copy(scope.row.orderid)">{{item.orderid}}</p>
        </div>
      </template>
    </el-table-column>
    <el-table-column prop="username" label="店铺账号" width="80" />
    <el-table-column prop="ordertime" label="下单时间"/>
    <!-- <el-table-column prop="address" label="SKU" width="120" show-overflow-tooltip=""/> -->
    <!-- <el-table-column prop="zip" label="产品数量（0）" width="120" /> -->
    <el-table-column prop="logisticsty" label="物流方式" width="100"  show-overflow-tooltip=""/>
    <el-table-column prop="waybillid" label="运单号（0）">
      <template v-slot="scope">
        <p  @click="copy(scope.row.waybillid)">{{scope.row.waybillid}}</p>
      </template>
    </el-table-column>
    <el-table-column prop="purchasing" label="采购成本（0）" width="120" >
      <template v-slot="scope">
        <el-input v-model="item.purchasing" placeholder="0" v-for="(item,index) in scope.row.list" :key="index" @keyup.enter="handelInput(item)"/>

      </template>
    </el-table-column>
    <el-table-column prop="freight" label="运费（0）" width="80" >
      <!-- <template v-slot="scope">
        <el-input v-model="scope.row.freight" placeholder="运费" @change="handelBlur(scope.row)"/>
      </template> -->
    </el-table-column>
    <el-table-column prop="notes" label="备注" width="160"  >
      <template v-slot="scope">
        <el-input
          v-model="scope.row.notes"
          @keyup.enter="dialogBeiZhu1(scope.row)"
          placeholder="备注"
          show-word-limit
          type="textarea"
        />
      </template>
    </el-table-column>
    <el-table-column prop="orderstate" label="签收情况" width="100" >
      <template v-slot="scope">
       {{ scope.row.orderstate == 0?'未采购': scope.row.orderstate == 1?'已采购': scope.row.orderstate == 2?'采购异常': scope.row.orderstate == 3?'已打单': scope.row.orderstate == 4?'已发货': scope.row.orderstate == 5?'已签收': scope.row.orderstate == 6?'签收异常': scope.row.orderstate == 7?'作废订单':'未采购'}}
      </template>
    </el-table-column>
    
    <el-table-column  label="操作" width="80">
      <template #default="scope">
        <el-button link type="primary" size="small"  @click="handeleAdd(scope.row)">修改</el-button>
      </template>
    </el-table-column>
  </el-table>
  <div class="demo-pagination-block">
    <el-pagination
      v-model:current-page="currentPage4"
      v-model:page-size="pageSize4"
      :page-sizes="[50, 100, 300]"
      :small="small"
      :disabled="disabled"
      :background="background"
      layout="total, sizes, prev, pager, next, jumper"
      :total="tabaleCount"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>

  <!-- 修改 -->
  <el-dialog v-model="dialogFormVisible" :title="title" width="500">
    <el-form :model="form" style="max-width: 460px">
      <!-- <el-form-item label="采购地址" :label-width="formLabelWidth">
        <el-input v-model="form.name" autocomplete="off" />
      </el-form-item> -->
      <el-form-item label="状态类型" :label-width="formLabelWidth">
        <el-select v-model="form.orderstate" placeholder="状态类型">
          <el-option
            v-for="item in orderstate"
            :key="item.value"
            :label="item.label"
            :value="item.value+''"
            >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="" :label-width="formLabelWidth">
        <el-timeline>
    <el-timeline-item
      :timestamp="cellRow.row.ordertime"
      type="primary"
      v-if="cellRow.row.ordertime!=''"
    >
    下单时间
    </el-timeline-item>
    
    <el-timeline-item
      :timestamp="cellRow.row.procuretime"
      v-if="cellRow.row.procuretime!=''"
      type="primary"
    >
    采购时间
    </el-timeline-item>
    <el-timeline-item
      :timestamp="cellRow.row.deliverytim"
      v-if="cellRow.row.deliverytim!=''"
      type="primary"
    >
    发货时间
    </el-timeline-item>
    <el-timeline-item
      :timestamp="cellRow.row.receivingti"
      v-if="cellRow.row.receivingti!=''"
      type="primary"
    >
    签收时间
    </el-timeline-item>
    <el-timeline-item
      :timestamp="cellRow.row.canceltime"
      v-if="cellRow.row.canceltime!=''"
      type="primary"
    >
    作废时间
    </el-timeline-item>
  </el-timeline>
       
      </el-form-item>
      <!-- <el-form-item label="运费" :label-width="formLabelWidth">
        <el-input v-model="form.freight" autocomplete="off" />
       
      </el-form-item> 
     <el-form-item label="备注" :label-width="formLabelWidth">
        <el-input
          v-model="form.notes"
          placeholder="备注"
          show-word-limit
          type="textarea"
        />
       
      </el-form-item> -->
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogFormVisible = false">关闭</el-button>
        <el-button type="primary" @click="dialogOrderstateupdate(cellRow.row)">
          确定
        </el-button>
      </span>
    </template>
  </el-dialog>
  <!-- 批量备注 -->
  <el-dialog v-model="dialogFormVisibleBeiZhu" :title="title" style="width: 500px;">
    <el-form :model="form">
     
      <el-form-item label="备注" :label-width="formLabelWidth">
        <el-input
          v-model="form.notes"
          placeholder="备注"
          show-word-limit
          type="textarea"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogFormVisibleBeiZhu = false">关闭</el-button>
        <el-button type="primary" @click="dialogBeiZhu(form)">
          确定
        </el-button>
      </span>
    </template>
  </el-dialog>
  <!-- 批量运费 -->
  <el-dialog v-model="dialogFormVisibleYunFei" :title="title" style="width: 500px;">
    <el-form :model="form">
     
      <el-form-item label="运费" :label-width="formLabelWidth">
        <el-input v-model="form.region" autocomplete="off" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogFormVisibleYunFei = false">关闭</el-button>
        <el-button type="primary" @click="dialogFormVisibleYunFei = false">
          确定
        </el-button>
      </span>
    </template>
  </el-dialog>
  <!-- 批量成本 -->
  <el-dialog v-model="dialogFormVisibleChengBen" :title="title" style="width: 500px;">
    <el-form :model="form">
     
      <el-form-item label="采购成功" :label-width="formLabelWidth">
        <el-input v-model="form.purchasing" autocomplete="off" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogFormVisibleChengBen = false">关闭</el-button>
        <el-button type="primary" @click="handelInput(form)">
          确定
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import useClipboard from "vue-clipboard3";
import { ref ,reactive,getCurrentInstance,onMounted,toRefs,onActivated,onUnmounted } from 'vue'
import {getLogin,getOrder,getOrderimport,getOrderimportfreight,getShop,download} from '@/api/service'
import { ElMessage,ElMessageBox  } from 'element-plus'
import type { UploadProps, UploadUserFile } from 'element-plus'
import { useRoute } from "vue-router"
const route = useRoute(); // 第一步
const currentPage4 = ref(1)
const pageSize4 = ref(50)
const small = ref(false)
const background = ref(false)
const disabled = ref(false)
const dialogFormVisible = ref(false)
const dialogFormVisibleBeiZhu = ref(false)
const dialogFormVisibleYunFei = ref(false)
const dialogFormVisibleChengBen = ref(false)

//注意哈，这里是个空
const timer = ref()
// 上传
const handlePreview: UploadProps['onPreview'] = (uploadFile:any) => {
  console.log(uploadFile)
  let file = uploadFile?.file;//拿到上传的file
  let param = new FormData();//创建form对象
  param.append("file", file);//为创建的form对象增加上传的文件
  param.append("id", "1");//如果需要上传其他字段，在这里增加
  let config = { headers: { "Content-Type": "multipart/form-data" } }//修改请求头
  let url = "你的上传地址";
  console.log(param)
  getOrderimport(param).then((res:any) => {
    console.log(res, "res");
    timer.value=setTimeout(() => {
      ElMessage({
        message: res.msg,
        type: res.code==1? 'success':'warning',
      })
   }, 1500)
  
  });
}
// 上传运费
const handlePreview1: UploadProps['onPreview'] = (uploadFile:any) => {
  console.log(uploadFile)
  let file = uploadFile?.file;//拿到上传的file
  let param = new FormData();//创建form对象
  param.append("file", file);//为创建的form对象增加上传的文件
  param.append("id", "1");//如果需要上传其他字段，在这里增加
  let config = { headers: { "Content-Type": "multipart/form-data" } }//修改请求头
  let url = "你的上传地址";
  console.log(param)
  getOrderimportfreight(param).then((res:any) => {
    console.log(res, "res");
    timer.value=setTimeout(() => {
      ElMessage({
        message: res.msg,
        type: res.code==1? 'success':'warning',
      })
   }, 1500)
  });
}
const { toClipboard } = useClipboard(); 
// const copyId = ref()
// 复制
const copy = async (item:any) => {
  // copyId.value = item;
  await toClipboard(item);
}
//在页面销毁之前先销毁定时器
onUnmounted(() => {
  clearTimeout(timer.value)
  timer.value=""
})

const title = ref('修改')
const formLabelWidth = '100px'
let ids  = reactive([])
let idslist = reactive([])
let single = reactive({
  data:true
}) 
const query = reactive(Object({
  page:1,
  count:50,
  notes:'',
  ordertimestart:'',
  ordertimeend:'',
  username:'',
  orderid:'',
  waybillid:'',
  orderstate:'',
}))
const { proxy } = getCurrentInstance() as any; 
const day =proxy.day
const data= reactive({
})
const refData = toRefs(data);
         
console.log(route.query.id,'--------');
onActivated(()=>{

})

const daoChu = () => {
  const queryRame = reactive(Object({
    notes:query.notes,
  ordertimestart:query.ordertimestart,
  ordertimeend:query.ordertimeend,
  username:query.username,
  orderid:query.orderid,
  waybillid:query.waybillid,
  // orderstate:query.orderstate,
  }))
  download("api/order.php?type=orderimport",queryRame,
        `introduction_${new Date().getTime()}.xlsx`
      );
  

}
const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`)
  query.value.count = val;
  getLoginQuery()

}
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`)
  query.value.page = val;
  getLoginQuery()
}
const size = ref<'default' | 'large' | 'small'>('default')
// 预览图片
const srcList = ref([])
// 搜索
const formInline = reactive({
  user: '',
  region: '',
  date: '',
})
const form = reactive({
  name: '',
  orderstate: '',
  freight: '',
  notes: '',
  region: '',
  purchasing:'',
})
const cellRow = reactive({
  row:{id: 0,ordertime:'',
procuretime:'',
deliverytim:'',
receivingti:'',
canceltime:'',}
})
// 选中的值
const selectName = ref('')
// 新增
const handeleAdd =(row:any)=>{
  dialogFormVisible.value = true;
  title.value = '修改'
  Object.assign(form, row)
  console.log(cellRow.row)
  cellRow.row = row;
}
const onSubmit = () => {
  console.log('submit!',formInline.user)
  for(let item in query.value) {
    if(isKey(item,query.value)){
		// 处理...
    if(selectName.value == item &&item !='ordertimestart') {
      query.value.ordertimestart = ''
      query.value.ordertimeend = ''
      query.value[item] = formInline.user || ''
    }
	}
 
}
  getLoginQuery()
}
// 定义一个函数：isKey()，然后对需要使用到的地方进行一次判断
function isKey(
    key: string | number | symbol,
    object: object
): key is keyof typeof object {
    return key in object;
}
// 批量
const onSubmit1 = (row:any) => {
  console.log('submit!')
  if(row==0) {
    title.value = '批量备注'
    dialogFormVisibleBeiZhu.value = true;
  } else if(row==1) {
    title.value = '批量运费'

    dialogFormVisibleYunFei.value = true;
  } else if(row==2) {
    title.value = '批量签收状态'
    dialogFormVisible.value = true;
  } else if(row==3) {
    title.value = '批量采购成本'
    dialogFormVisibleChengBen.value = true;
  }
}
const isShop = ref(false);
const getLoginQuery1 = ()=>{
  let data = {
    type:'query',
  }
  getLogin(data).then((res:any)=>{
    console.log(res)
    if(res.code==1) {
      let user = localStorage.getItem('user')
      console.log(user)
      
      for(let item of res.list) {
        if(user == item.user) {
          isShop.value = item.type == 1 ?false:true
        }
      }
      return 
    }
 
    ElMessage({
      message: res.msg,
      type: 'warning',
    })
  })
}
const dialogBeiZhu = (row:any) => {
  let data = {
    type:'ordersetnotes',
    ids:ids.join() || row.id,
    notes:row.notes
  }
  getOrder(data).then((res:any)=>{
    console.log(res)
  dialogFormVisibleBeiZhu.value = false;
  single.data = true;
  getLoginQuery()
    if(res.code==1)  {
      ElMessage({
        message: res.msg,
        type: 'success',
      })
      return
    }
 
    ElMessage({
      message: res.msg,
      type: 'warning',
    })
  })
}
const dialogBeiZhu1 = (row:any) => {
  let data = {
    type:'ordersetnotes',
    ids:row.id,
    notes:row.notes
  }
  getOrder(data).then((res:any)=>{
    console.log(res)
  
    if(res.code==1)  {
      ElMessage({
        message: res.msg,
        type: 'success',
      })
      return
    }
 
    ElMessage({
      message: res.msg,
      type: 'warning',
    })
  })
}
const handelInput = (row:any) => {
  console.log(row)
  let data = {
    type:'ordersukpurchasing',
    ids:row?.id||idslist.join(','),
    purchasing:row?.purchasing
  }
  getOrder(data).then((res:any)=>{
    console.log(res)
    // getLoginQuery()
    dialogFormVisibleChengBen.value = false
    if(res.code==1)  {
      ElMessage({
        message: res.msg,
        type: 'success',
      })
      return
    }
 
    ElMessage({
      message: res.msg,
      type: 'warning',
    })
  })
}
const handelBlur = (row:any) =>{
  let data = {
    type:'ordersetfreight',
    id:row.id,
    freight:row.freight
  }
  getOrder(data).then((res:any)=>{
    console.log(res)
    // getLoginQuery()
    if(res.code==1)  {
      ElMessage({
        message: res.msg,
        type: 'success',
      })
      return
    }
 
    ElMessage({
      message: res.msg,
      type: 'warning',
    })
  })
}
// 修改订单状态
const dialogOrderstateupdate = (row:any) =>{
  console.log(row)
  let data = {
    type:'orderstateupdate',
    ids:row.id !=0 ? row.id : ids.join(','),
    state:form.orderstate
  }
  getOrder(data).then((res:any)=>{
    console.log(res)
    getLoginQuery()
    dialogFormVisible.value= false;
    if(res.code==1)  {
      ElMessage({
        message: res.msg,
        type: 'success',
      })
      return
    }
 
    ElMessage({
      message: res.msg,
      type: 'warning',
    })
  })
}
// 多选框选中数据
const handleSelectionChange = (selection:any)=> {
  ids = selection.map((item:any) => item.id);
  idslist = selection.map((item:any) => {
    for(let items of item?.list) {
      return items.id
    }
  });
  // console.log(idslist)
  // for(let item of selection) {
  //   for(let items of item?.list) {
  //     console.log(items.id)
  //     idslist.list.push(items.id)
  //   }
  // }

  single.data = !single.data;
//操作数据后更新视图
// internalInstance.ctx.$forceUpdate()
  console.log(single)
}
// 单选框选中数据
const handleSelection = (selection:any,row:any)=> {
  ids = selection.map((item:any) => item.id);
  idslist = selection.map((item:any) => {
    for(let items of item?.list) {
      return items.id
    }
  });
  single.data = ids.length>=1?false:true;
//操作数据后更新视图
// internalInstance.ctx.$forceUpdate()
  console.log(single)
}
// 表格数据
const tableData = ref([])
let tabaleCount = Number(0)
onMounted(()=>{
  query.orderstate = route.query.id || '';
  getLoginQuery();
  getShopQuery();
  getLoginQuery1();
})
let tableDataList = ref([{
  id:'',
  name:'',
}])
const getShopQuery = ()=>{
  let data = {
    type:'query',
    
  }
  getShop(data).then((res:any)=>{
    if(res.code==1) return tableDataList.value = res.list
 
    ElMessage({
      message: res.msg,
      type: 'warning',
    })
  })
}
// 搜索选中的值
const hanldeChange =(val:any)=>{
  selectName.value = val

}
// 选择日期
const handelDatePicker =(val:any)=>{
  console.log(val,'---------------')
  query.value.ordertimestart = val!=null?day(val[0]).format('YYYY-MM-DD HH:mm:ss'):''
  query.value.ordertimeend =val!=null? day(val[1]).format('YYYY-MM-DD HH:mm:ss'):''

}
// 获取订单列表
const getLoginQuery = ()=>{
  // 重置
  tableData.value=[]
  console.log(query.value)
  let data = {
    type:'query',
    orderstate:route.query.id || ''
    
    // page:query.value.page,
    // count:query.value.count,
  }
  // Reflect.set(data, query+'', formInline.user)
  Object.assign(data,query.value)
  let itemImg = []
  getOrder(data).then((res:any)=>{
    console.log(res)
    if(res.code==1)  {
      tableData.value = res.list
      tabaleCount =  Number(res.data.count)
      console.log(tabaleCount,typeof(res.data.count))
      for(let item of res.list) {
        itemImg = item.list.map((res:any)=>{
          res.img
        })
        Reflect.set(item, 'imgs', itemImg)
      }
      return
    }
 
    ElMessage({
      message: res.msg,
      type: 'warning',
    })
  })
}
const orderstate = [
{
  label: '未采购',
  value: 0,
},
{
  label: '已采购',
  value: 1,
},{
  label: '采购异常',
  value: 2,
},{
  label: '已打单',
  value: 3,
},{
  label: '已发货',
  value: 4,
},{
  label: '已签收',
  value: 5,
},{
  label: '签收异常',
  value: 6,
},{
  label: '作废订单',
  value: 7,
},
];

// 表单数据
const formList = ref([
// {
//   label: '包裹号',
//   value: 0,
//   id:''
// },
{
  label: '订单号',
  value: 1,
  id:'orderid'
},{
  label: '店铺账号',
  value: 2,
  id:'username'
},{
  label: '下单时间',
  value: 3,
  id:'ordertimestart'
},
// {
//   label: 'SKU',
//   value: 4,
//   id:'sku'
// },
{
  label: '运单号',
  value: 5,
  id:'waybillid'
},
// {
//   label: '运费',
//   value: 6,
//   id:''
// },
{
  label: '备注',
  value: 7,
  id:'notes'
},
])

</script>
<style scoped>
.demo-pagination-block + .demo-pagination-block {
  margin-top: 10px;
}
.demo-pagination-block .demonstration {
  margin-bottom: 16px;
}
.demo-form-inline .el-input {
  --el-input-width: 220px;
}
/* 图片 */
.ImageFD {
  width: 100px;
  min-height: 30px;
  max-height: 100px;
}
::v-deep(.el-select-v2) {
  width: 120px;
}
.flex {
  display: flex;
  /* justify-content: space-between; */
}
.flex_right {
  margin-left: 20px;
}
::v-deep(.el-upload-list) {
  display: none;
}
.upload-demo {
  margin: 0 20px;
}
</style>